import React,{Component} from "React" 
import {
    Platform,
    StyleSheet,
    Text,
    Image,
    View,
    Alert,
    TextInput,
    Slider,
    Flatlist,
    ScrollView,
    TouchableOpacity,
} from 'react-native';
import pxToDp from '../config/pxToDp';
import Emoticons from 'react-native-emoticons';
import  XMPP from 'react-native-xmpp'
import HeaderChild from '../ui/headerChild';
import Config from '../config/config'
import getData from '../config/fetch'
import { GiftedChat } from 'react-native-gifted-chat'
import px2dp from '../config/pxToDp';
// icon
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import SimpleLineIcons from 'react-native-vector-icons/SimpleLineIcons';
var Url = Config.Url
var Host = Config.host
export default class ChatScene extends Component{
    state = {
        messages: [],
    }
    constructor(props){
        super(props)
        let _Options = Array({
                name: 'burst-mode',
                text: '相册',
            }, {
                name: 'burst-mode',
                text: '拍摄',
            }, {
                name: 'burst-mode',
                text: '视频通话',
            },
            //  {
            //     name: 'burst-mode',
            //     text: '位置',
            // }, {
            //     name: 'burst-mode',
            //     text: '红包',
            // }, {
            //     name: 'burst-mode',
            //     text: '转账',
            // }, {
            //     name: 'burst-mode',
            //     text: '名片',
            // }, {
            //     name: 'burst-mode',
            //     text: '文件',
            // }, 
        )
        this.state = {
            messages: [],
            loadEarlier: true,
            typingText: null,
            isLoadingEarlier: false,
            msgLength: 0,
            msg: null,
            micOrText:0,
            minInputToolbarHeight:44,
            isEmoji:false,
            isExtra:false,
            _Options: _Options,
        };
        

        //获取传值
        //this.props.navigation.state.params.xxx
        // optional callbacks
        XMPP.on('message', (message) => {
            // console.log('MESSAGE:' + JSON.stringify(message))
            console.log('MESSAGE:' + message.body)
            let data = JSON.parse(message.body)

            this.onReceive(data.content)
        });
        //XMPP.on('iq', (message) => console.log('IQ:' + JSON.stringify(message)));
        //XMPP.on('presence', (message) => console.log('PRESENCE:' + JSON.stringify(message)));
        XMPP.on('error', (message) => console.log('ERROR:' + JSON.stringify(message)));
        XMPP.on('loginError', (message) => console.log('LOGIN ERROR:' + JSON.stringify(message)));
        XMPP.on('login', (message) => console.log('LOGGED!' + JSON.stringify(message)));
        XMPP.on('connect', (message) => console.log('CONNECTED!'));
        XMPP.on('disconnect', (message) => console.log('DISCONNECTED!' + JSON.stringify(message)));
        XMPP.trustHosts([Host]);
        let domain = 'desktop-3f8o46c'        
        // connect
        // XMPP.connect('111111@' + domain, '111111', '', '192.168.31.14');
        storage.load({
                key: 'loginState',
            }).then(ret => {
                //获得密钥
                getData.getData("?m=User&c=Api&a=openfirePwd", "", this.props).then(data => {

                    var mindId = ret.userId
                    let jid = ret.userId + '@' + data.data.computerName.toLowerCase();
                    let pwd = data.data.encryptedPassword;
                    console.log(data);
                    XMPP.connect(jid, pwd, '', Host);
                    // XMPP.connect('200100@' + domain, '165588', '', '192.168.31.14');
                })

            })

        // send message

        // XMPP.message('Hello world!', '200093@' + domain);

        // disconnect
        // XMPP.disconnect();

        // remove all event listeners (recommended on componentWillUnmount)
        // XMPP.removeListeners();

        // remove specific event listener (type can be 'message', 'iq', etc.)
        XMPP.removeListener('iq');
        XMPP.removeListener('presence');
        
    }

    componentWillMount() {
        //可以加载聊天记录
        console.log(uid + 'chatlist' + this.props.navigation.state.params.friendUid)
        storage.getAllDataForKey(uid + 'chatlist' + this.props.navigation.state.params.friendUid).then(ids => {
            console.log(ids);
            this.setState((previousState) => {
                return {
                    messages: GiftedChat.prepend(previousState.messages, ids.reverse()),
                    loadEarlier: false,
                    isLoadingEarlier: false,
                };
            });
        });

        // this.setState({
        //     messages: [
        //         {
        //             _id: 1,
        //             text: '你好',
        //             createdAt: new Date(),
        //             user: {
        //                 _id: 2,
        //                 name: 'React Native',
        //                 avatar: 'https://placeimg.com/140/140/any',
        //             },
        //         },
        //     ],
        // })
    }
    componentWillUnmount(){
        console.log('断开连接')
        // XMPP.disconnect();
    }
    //加载早期消息的回调
    onLoadEarlier() {
        console.log("加载更早")
        this.setState((previousState) => {
            return {
                isLoadingEarlier: true,
            };
        });

        setTimeout(() => {
            if (this._isMounted === true) {
                this.setState((previousState) => {
                    return {
                        messages: GiftedChat.prepend(previousState.messages, require('../config/old_messages')),
                        loadEarlier: false,
                        isLoadingEarlier: false,
                    };
                });
            }
        }, 1000); // simulating network
    }
    onReceive(text) {
        console.log(this.props.navigation.state.params.friendPic)
        this.setState((previousState) => {
            let msg = {
                _id: Math.round(Math.random() * 1000000) + '-nwidc-' + Math.round(Math.random() * 1000000),
                text: text,
                // image:text,
                createdAt: new Date(),
                user: {
                    _id: this.props.navigation.state.params.friendUid,
                    name: 'React Native',
                    avatar: this.props.navigation.state.params.friendPic,
                },
            }
            this.saveMsg(msg)
            return {
                messages: GiftedChat.append(previousState.messages, msg),
            };
        });
    }
    //save Massage
    saveMsg(msg){
        // 获取某个key下的所有id(仅key-id数据)
        storage.getIdsForKey(uid + 'chatlist' + this.props.navigation.state.params.friendUid).then(ids => {
            let length = ids.length
            console.log(length)
            storage.save({
                key: uid+'chatlist' + this.props.navigation.state.params.friendUid, // 注意:请不要在key中使用_下划线符号!
                id: length+1, // 注意:请不要在id中使用_下划线符号!
                data: msg,
            });
        });
    }
    //send
    onSend(messages = []) {
        console.log(messages)
        this.setState(previousState => ({
            messages: GiftedChat.append(previousState.messages, messages),
        }))
        this.saveMsg(messages)
        this.funSend(messages.text)
        // /index.php?m=User&c=Api&a=sendMessage&uid=200020&toid=200058&content=dal
        // this.saveMsg(this.props.navigation.state.params.friendUid,)
    }

    funSend(message){
        console.log(message)

        fetch(Url + "?m=User&c=Api&a=sendMessage", {
            method:"POST",
            headers:{
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: "&uid=" + uid + "&toid=" + this.props.navigation.state.params.friendUid + "&content=" + message
        }).then(res=>{
            res.json().then(data=>{
                console.log(data)
            })
        })
    }
    msgInput(){
        return(
            <View style={{height:this.state.minInputToolbarHeight,flexDirection:'column'}}>
                <View style={{height:44, paddingLeft:8,paddingRight:8,flexDirection:'row',borderTopWidth:1,borderColor:"#f9f9f9",}}>
                
                    < View style = {styles.metric} >
                        <TouchableOpacity style={styles.roundIcon} onPress={()=>{
                            this.setState({
                                micOrText: !this.state.micOrText,
                                minInputToolbarHeight: 44,
                                isExtra: false,
                            });
                        }}>
                            {this.state.micOrText == 0 ? (
                                <MaterialIcons name='keyboard-voice' size={25} />
                            ):(
                                <MaterialIcons name='keyboard' size={25} />
                            )}
                            
                        </TouchableOpacity>
                    </View>
                    < View style = {styles.optionInput} >
                        {this.state.micOrText == 0 ?(
                            <TextInput style={[styles.msginput,styles.msgInputBorder]}
                                underlineColorAndroid = "transparent"
                                value = {this.state.msg}
                                onFocus={() => this.setState({ minInputToolbarHeight: 44,})}
                                onChangeText ={text=>{
                                    this.setState({
                                        msgLength: text.length,
                                        msg: text,
                                    })
                                }}
                            />
                        ):(
                            <View style={[styles.msginput,styles.micinput]}>
                                <Text>
                                    按住说话
                                </Text>
                            </View>
                        )}
                        
                    </View>
                    < View style = {styles.moreOption} >
                        <TouchableOpacity style = {styles.metric} onPress={()=>{
                            var height = this.state.minInputToolbarHeight == 44 ? 300 : 44;
                                //如果弹窗已经打开
                                if (this.state.isExtra == true){
                                    //如果显示是Emoji
                                    if (this.state.isEmoji == true) {
                                        //直接关闭
                                        this.setState({
                                            minInputToolbarHeight: 44,
                                            micOrText: 0,
                                            isExtra: false
                                        })
                                    }else{
                                        //如果不是
                                        //切换成当前
                                        this.setState({
                                            isEmoji: true,
                                        })
                                    }
                                    
                                }else{
                                    console.log('弹窗未打开，现在打开')
                                    this.setState({
                                        minInputToolbarHeight: 300,
                                        micOrText: 0,
                                        isEmoji: true,
                                        isExtra: true
                                    })
                                }
                                
                        }}>
                            <SimpleLineIcons name='emotsmile' size={30} />
                        </TouchableOpacity>
                        <View style = {styles.metric}>
                            {this.state.msgLength != 0 ? (
                                    <TouchableOpacity style={styles.send}
                                        // autoFocus={true}
                                        blurOnSubmit={false}
                                        multiline={true}
                                        onPress={()=>{
                                            let msg = {
                                                    _id: Math.round(Math.random() * 1000000) + "-nwidc-" + Math.round(Math.random() * 1000000),
                                                    text: this.state.msg,
                                                    createdAt: new Date(),
                                                    user: {
                                                        _id: parseInt(uid),
                                                    }
                                                }
                                            this.onSend(msg);
                                            this.setState({
                                                msgLength:0,
                                                msg: null,
                                            })
                                        }}    
                                    >
                                        <Text style={styles.sendSty}>
                                            发送
                                        </Text>
                                    </TouchableOpacity>
                                ):(
                                    <TouchableOpacity style={styles.roundIcon} onPress={() => {
                                        var height = this.state.minInputToolbarHeight == 44 ? 300 : 44;
                                        //如果弹窗已经打开
                                        if (this.state.isExtra == true){
                                            //如果显示是Exrta
                                            if (this.state.isEmoji == false) {
                                                //直接关闭
                                                this.setState({
                                                    minInputToolbarHeight: 44,
                                                    micOrText: 0,
                                                    isExtra: false
                                                })
                                            }else{
                                                //如果不是
                                                //切换成当前
                                                this.setState({
                                                    isEmoji: false,
                                                })
                                            }
                                            
                                        }else{
                                            this.setState({
                                                minInputToolbarHeight: 300,
                                                micOrText: 0,
                                                isEmoji: false,
                                                isExtra: true
                                            })
                                        }
                                        
                                    }}>
                                        <MaterialIcons name='add' size={25} />
                                    </TouchableOpacity>
                                )
                                
                            }
                        </View>
                    </View>
                </View>
                    {this.state.minInputToolbarHeight == 300 ? (
                        <View style={styles.extra}>
                            {this.state.isExtra == 1 ? (
                                this.state.isEmoji == 1 ? (
                                    <Emoticons
                                        style={{}}
                                        onEmoticonPress={T=>{
                                            console.log(T)
                                        }}
                                        onBackspacePress={()=>{
                                            
                                        }}
                                        show={true}
                                        concise={false}
                                        showHistoryBar={true}
                                        showPlusBar={true}
                                    />
                                ) : (
                                    <View style={styles.experience}>
                                        <View style={{flexDirection:'row',flexWrap:'wrap'}}>
                                            {/* <Flatlist
                                                renderItem={(data)=>{
                                                    return(
                                                        <View style={styles.square}> 
                                                            <MaterialIcons name="burst-mode" size={40}/>
                                                            <Text>
                                                                相册
                                                            </Text>
                                                        </View>
                                                    )
                                                } }
                                                // data={this.state._Options}
                                                data={[
                                                    'd',
                                                    'd',
                                                    'd',
                                                ]}
                                            /> */}
                                            <View style={styles.square}> 
                                                <MaterialIcons name="burst-mode" size={40}/>
                                                <Text>
                                                    相册
                                                </Text>
                                            </View>
                                            <View style={styles.square}> 
                                                <MaterialIcons name="burst-mode" size={40}/>
                                                <Text>
                                                    相册
                                                </Text>
                                            </View>
                                            <View style={styles.square}> 
                                                <MaterialIcons name="burst-mode" size={40}/>
                                                <Text>
                                                    相册
                                                </Text>
                                            </View>
                                        </View>
                                    </View>
                                )
                            ) : (
                                null
                            )}
                            
                        </View>
                    ):(
                        null
                    )}
                
                
            </View>
        )
    }
    extraFunS(){
        return(
            <View style={styles.extra}>
                <Text>
                    231
                </Text>
            </View>
        )
    }
    render() {
        return (
            
            <View style={ styles.chat}>
                <View >
                    <HeaderChild clickBack={() => this.props.navigation.goBack()} 
                        rightClick={()=>{
                            this.props.navigation.navigate('chatInfoScene')
                        }}
                        title={this.props.navigation.state.params.friendName}
                    />
                </View>
                <GiftedChat
                    messages={this.state.messages}
                    onSend={messages => this.onSend(messages)}
                    showUserAvatar={true}
                    // loadEarlier={true}
                    onLoadEarlier={this.onLoadEarlier.bind(this)}
                    alwaysShowSend={true}
                    placeholder=""
                    // renderAccessory={()=>{
                    //     return(
                    //         <View style={{height:400}}>
                    //             <Text>2264738291463789246718946279832</Text>
                    //         </View>
                    //     )
                    // }}
                    dateFormat='YYYY-MM-DD H:MM'
                    renderChatFooter   = {this.msgInput.bind(this)}
                    minInputToolbarHeight={0}
                    // minInputToolbarHeight={this.state.minInputToolbarHeight}
                    renderInputToolbar = {
                        // this.extraFunS.bind(this)
                        // this.extraFunS.bind(this)
                        ()=>{
                            return(
                                <View>
                        </View>
                            )
                        }
                    }
                    
                    user={{
                        _id: parseInt(uid),
                        avatar: 'https://placeimg.com/140/140/any',
                    }}
                />
            </View>
            
        )
    }

} 

const styles={
    chat:{
        flex: 1,
        backgroundColor:'#fff'
    },
    option:{
        borderTopWidth:1,
        borderColor:"#f9f9f9",
        // flexDirection:'row',
        // flex: 1,
        
    },
    roundIcon:{
        borderWidth:2,
        borderColor:"#757575",
        borderRadius:50,
    },
    msgInputBorder:{
        padding:0,
        borderBottomWidth:1,
        borderColor: "#009688",
    },
    metric:{
        width:px2dp(85),
        justifyContent: 'center',
        alignItems: 'center',
    },
    optionInput:{
        width: px2dp(370),
        justifyContent: 'center',
        alignItems:'center',
        flex:1
    },
    moreOption:{
        justifyContent: 'center',
        alignItems:'center',
        flexDirection:"row",
    },
    msginput:{
        width:px2dp(350),
        justifyContent: 'center',
        alignItems: 'center',
    },
    micinput:{
        borderWidth:1,
        borderRadius:5,
        height:30,
        borderColor:"#c9c9c9",
    },
    send:{
        justifyContent:"center",
        borderWidth: 1,
        borderColor: "#02B1F8",
        borderRadius: 5,
        width:px2dp(75),
        height:30,
        backgroundColor: "#02B1F8",
    },
    sendSty:{
        alignSelf: 'center',
        color:'#fff',
    },
    extra:{
        height:300
    },
    experience:{
        paddingTop:15,
        paddingBottom:15,
    },
    square:{
        width:px2dp(110),
        height:px2dp(110),
        marginLeft: px2dp(25),
        marginRight: px2dp(25),
        justifyContent:'center',
        borderWidth:1,
        alignItems:'center',
        borderColor:"rgb(117,117,117)",
        borderRadius:10,
    },
}